<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="550" :visible="visible" :confirmLoading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading">
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" layout="vertical" class="common-modal-content">
        <a-row :gutter="24">
          <a-col :span="19">
            <a-row>
              <a-col :span="24">
                <a-form-item :label="$t('other.theNumberOfTheBridge')" name="code" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-model:value.trim="formState.code" :disabled="isEdit" :placeholder="$t('other.autoGenerate')" />
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label="$t('other.startingMainRail')" name="startMasterTrackId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('other.startingMainRail') }]">
                  <a-select v-model:value="formState.startMasterTrackId" @change="() => getBridgeList(null)" :placeholder="$t('common.pleaseSelect')">
                    <a-select-option v-for="item in trackList" :key="item.key" :value="item.id" >{{item.masterTrackNo}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="24" >
                <a-form-item :label="$t('other.destinationMasterTrack')" name="endMasterTrackId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: $t('other.destinationMasterTrack') }]" >
                  <a-select v-model:value.trim="formState.endMasterTrackId" @change="() => getBridgeList(null)" :placeholder="$t('common.pleaseSelect')">
                    <a-select-option v-for="item in trackList" :key="item.key" :value="item.id" >{{item.masterTrackNo}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item :label="$t('deviceManage.bridgeNo')" name="hangerLineBridgeId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: t('other.pleaseSelectTheBridgeNumber') }]">
                  <a-select v-model:value="formState.hangerLineBridgeId" allowClear :placeholder="$t('common.pleaseSelect')" :disabled="!(formState.startMasterTrackId && formState.endMasterTrackId)">
                    <a-select-option v-for="(item,i) in roadList" :value="item.id" :key="i">
                      {{item.code}}
                      ( {{ item.astation }}
                      {{ item.direction ==1 ? '<-': item.direction ==2?'<->':'->' }}
                      {{ item.bstation }} )
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

          </a-col>
        </a-row>

      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="addDialog">
import { nextTick, ref, onBeforeMount, computed } from 'vue'
import axios from '@/utils/request'
import {cloneDeep } from 'lodash'
import { message } from "ant-design-vue"
import {  getFieldText } from '@/utils'
import {store} from "@/store"
import i18n from "@/locales/index"

const { t } = i18n.global
const emits = defineEmits(['ok'])
const labelCol = { xs: { span: 24 }, sm: { span: 23 } }
const wrapperCol = { xs: { span: 24 }, sm: { span: 23 } }
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let roadList = ref([])
const trackList = computed(() => {
  return store.state.normalData.trackList
});

const edit = async (record, editable) => {
  initModalData(record, editable)
  await getBridgeList(record)
  await nextTick()
  formRef.value.resetFields()
  formState.value = cloneDeep(record)
}
const initModalData = (record, editable) => {
  title.value = editable? t('other.editTheBridge') : t('other.addTheBridge')
  // title.value = '编辑跨线桥接';
  recordInfo.value = Object.assign({}, record)
  visible.value = true
  isEdit.value = editable
}

const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    if ( values.startMasterTrackId == values.endMasterTrackId){
      message.warn(t('other.theMainTrackIsNotTheSame'))
      return
    }
    let params = doParam(values)
    let url = isEdit.value ? '/api/device/bridge-cross/update' : '/api/device/bridge-cross/save'
    console.log(params)
    const res = await axios.postAction(url, params)
    if (res.success) {
      emits('ok')
      confirmLoading.value = false // 刷新
      visible.value = false
      initModalStatus()
      message.success(t('common.doSuccess'))
    }
  } catch (err) {
    console.log('0000000', err);
  }
  confirmLoading.value = false
};

const doParam = (values) => {
  values.startLineId = getFieldText(trackList.value, values.startMasterTrackId,'id','hangerLineId')
  values.endLineId = getFieldText(trackList.value, values.endMasterTrackId, 'id','hangerLineId')
  values.status = 1
  if (isEdit.value){
    values.id = formState.value.id || ''
  }
  return values
}

const handleCancel = () => {
  visible.value = false
  initModalStatus()
}
const initModalStatus = () => {
  confirmLoading.value = false
  formState.value = {}
  formRef.value.resetFields()
  roadList.value = []
  trackList.value = []
}

const getBridgeList = async (record) => {
  let {startMasterTrackId, endMasterTrackId} = record ? record : formState.value
  if(startMasterTrackId && endMasterTrackId) {
    let res = await axios.postAction('/api/device/hanger-line-bridge/list',{"pageNo": 1, "pageSize": 60000,amasterTrackId:startMasterTrackId, bmasterTrackId: endMasterTrackId})
    // console.log( res?.data.list)
    roadList.value = res?.data.list || []
  } else {
    roadList.value =  []
  }
  formState.value.hangerLineBridgeId = undefined
}
onBeforeMount(async () => {
  await store.dispatch('getTrack')
  console.log(trackList.value)
})
defineExpose({
  edit,
})

</script>